package sdk.webview.fmc.com.fmcsdk.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.WebIconDatabase;
import com.tencent.smtt.sdk.WebStorage;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import sdk.webview.fmc.com.fmcsdk.R;
import sdk.webview.fmc.com.fmcsdk.app.FMCApplication;
import sdk.webview.fmc.com.fmcsdk.base.BaseActivity;
import sdk.webview.fmc.com.fmcsdk.bean.DDTypeBean;
import sdk.webview.fmc.com.fmcsdk.bean.SystemSetting;
import sdk.webview.fmc.com.fmcsdk.check.CacheHelper;
import sdk.webview.fmc.com.fmcsdk.db.DBManager;
import sdk.webview.fmc.com.fmcsdk.db.DatabaseManager;
import sdk.webview.fmc.com.fmcsdk.db.IMAGE;
import sdk.webview.fmc.com.fmcsdk.db.Record;
import sdk.webview.fmc.com.fmcsdk.interfaces.SettingView;
import sdk.webview.fmc.com.fmcsdk.presenter.SettingPresenter;
import sdk.webview.fmc.com.fmcsdk.util.CacheDataManager;
import sdk.webview.fmc.com.fmcsdk.util.Constant;
import sdk.webview.fmc.com.fmcsdk.util.KLog;
import sdk.webview.fmc.com.fmcsdk.util.Language;
import sdk.webview.fmc.com.fmcsdk.util.PreferencesHelper;
import sdk.webview.fmc.com.fmcsdk.util.StringUtils;
import sdk.webview.fmc.com.fmcsdk.util.TitleBar;
import sdk.webview.fmc.com.fmcsdk.util.ToastUtils;
import sdk.webview.fmc.com.fmcsdk.util.Utility;
import sdk.webview.fmc.com.fmcsdk.view.GPSCustomDialog;
import sdk.webview.fmc.com.fmcsdk.view.LangDialog;
import sdk.webview.fmc.com.fmcsdk.view.SwitchView;

/**
 * 设置
 */
public class SettingActivity extends BaseActivity<SettingView, SettingPresenter> implements View.OnClickListener, SettingView {

    //清理缓存数据的handler
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    hideLoading();
                    ToastMessage(getResources().getString(R.string.clean_success));

                    try {
                        tvData.setText(CacheDataManager.getTotalCacheSize(SettingActivity.this));
                        startHome();

                    } catch (Exception e) {
                        hideLoading();
                        e.printStackTrace();
                    }
                    break;
                case 1:
                    hideLoading();
                    ToastMessage(getResources().getString(R.string.clean_failure));
                    break;
            }
        }
    };

    private final int LANG_DIALOG = 6;
    int selectLang;
    RelativeLayout notifySetting;
    RelativeLayout uploadLog;
    TitleBar titlebar;
    RelativeLayout rlFeedback;
    RelativeLayout rlClear;
    RelativeLayout rlAbout;
    RelativeLayout settingSwitchLanguageLl;
    TextView tvLangHint;
    SwitchView sound_cb;
    SwitchView vibrate_cb;
    SwitchView wifi_up_cb;
    SwitchView openUploadLog;
    RelativeLayout rlNfc;
    RelativeLayout rlNewTaskSound;
    RelativeLayout rlGrabTaskSound;
    RelativeLayout rlMessageNoticeSound;
    RelativeLayout rl_expire_sound;
    RelativeLayout rl_yinsi_xiyi;
    private final int NEW_CODE = 1;
    private final int GRAB_CODE = 2;
    private final int MESSAGE_CODE = 3;
    private final int EXPIRE_CODE = 4;
    TextView tvNewSound;
    TextView tvGrabSound;
    TextView tvMessageSound;
    TextView tvData;

    TextView tv_expire_sound;
    private DatabaseManager databaseManager;
    private DialogInterface dialogs;
    private List<DDTypeBean.RecordsBean> langArrayList = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_setting;
    }
    @Override
    protected void init(Bundle savedInstanceState) {
       List<Record> imagList = DBManager.getDBManager(context).getRecords(IMAGE.TABLE_NAME, null);
        if(imagList==null||imagList.size()==0){
            CacheDataManager.clearLubanCache(context);
        }
        findView();
        //设置缓存数据大小
        databaseManager = new DatabaseManager(context);
        try {
            tvData.setText(CacheDataManager.getTotalCacheSize(this));
        } catch (Exception e) {
            e.printStackTrace();
        }
        titlebar.setTitle(getString(R.string.system_setting));
        //设置点击事件
        sound_cb.setState(sharedPrefs.getBoolean(Constant.SOUND, false));
        vibrate_cb.setState(sharedPrefs.getBoolean(Constant.VIBRATE, false));
        wifi_up_cb.setState(sharedPrefs.getBoolean(Constant.WIFI_UP, false));
        openUploadLog.setState(sharedPrefs.getBoolean(Constant.OPEN_START_MODE, false));
        rlFeedback.setOnClickListener(this);
        rlAbout.setOnClickListener(this);
        rlNfc.setOnClickListener(this);
        rlNewTaskSound.setOnClickListener(this);
        rlGrabTaskSound.setOnClickListener(this);
        rlMessageNoticeSound.setOnClickListener(this);
        rlClear.setOnClickListener(this);
        rl_yinsi_xiyi.setOnClickListener(this);
        notifySetting.setOnClickListener(this);
        uploadLog.setOnClickListener(this);
        //初始化侧滑按钮
        onSwitchListener();
        settingSwitchLanguageLl.setOnClickListener(this);
        //语言设置
        selectLang = sharedPrefs.getInt("lang", 0);
        tvLangHint.setText(getResources().getStringArray(R.array.multi_language)[selectLang]);
        //设置声音
        tvGrabSound.setText(sharedPrefs.getString(Constant.SOUND_GRAB_NAME, getString(R.string.default_text)));
        tvNewSound.setText(sharedPrefs.getString(Constant.SOUND_NEW_NAME, getString(R.string.default_text)));
        tvMessageSound.setText(sharedPrefs.getString(Constant.SOUND_MESSAGE_NAME, getString(R.string.default_text)));
        tv_expire_sound.setText(sharedPrefs.getString(Constant.SOUND_EXPIRE_NAME, getString(R.string.default_text)));


//        String xieyiStr = StringUtils.getActivityPlaceholders(this, "YINSI_XIEYI_URL");
//        if (TextUtils.isEmpty(xieyiStr)) {
//            rl_yinsi_xiyi.setVisibility(View.GONE);
//        } else {
//            rl_yinsi_xiyi.setVisibility(View.VISIBLE);
//        }


    }

    @Override
    protected void onResume() {
        super.onResume();
        String grabname = sharedPrefs.getString(Constant.SOUND_GRAB_NAME, getString(R.string.default_text));
        if (grabname.equals("默认") || grabname.equals("Default") || grabname.equals("默認")) {
            tvGrabSound.setText(getString(R.string.default_text));
        } else {
            tvGrabSound.setText(grabname);
        }

        String newname = sharedPrefs.getString(Constant.SOUND_NEW_NAME, getString(R.string.default_text));
        if (newname.equals("默认") || newname.equals("Default") || newname.equals("默認")) {
            tvNewSound.setText(getString(R.string.default_text));
        } else {
            tvNewSound.setText(newname);
        }

        String messagename = sharedPrefs.getString(Constant.SOUND_MESSAGE_NAME, getString(R.string.default_text));
        if (messagename.equals("默认") || messagename.equals("Default") || messagename.equals("默認")) {
            tvMessageSound.setText(getString(R.string.default_text));
        } else {
            tvMessageSound.setText(messagename);
        }


        String expirename = sharedPrefs.getString(Constant.SOUND_EXPIRE_NAME, getString(R.string.default_text));
        if (expirename.equals("默认") || expirename.equals("Default") || expirename.equals("默認")) {
            tv_expire_sound.setText(getString(R.string.default_text));
        } else {
            tv_expire_sound.setText(expirename);
        }


        SystemSetting systemSetting = PreferencesHelper.getData(SystemSetting.class);
        if (systemSetting != null) {
            String mobile_font_color = systemSetting.getRecord().getMOBILE_FONT_COLOR();
            if (!TextUtils.isEmpty(mobile_font_color)) {
                tvLangHint.setTextColor(Color.parseColor(mobile_font_color));
            }
        }
    }

    private void findView() {
        notifySetting = (RelativeLayout) findViewById(R.id.notify_setting);
        uploadLog = (RelativeLayout) findViewById(R.id.upload_log);
        titlebar = (TitleBar) findViewById(R.id.titlebar);
        rlFeedback = (RelativeLayout) findViewById(R.id.rl_feedback);
        rlClear = (RelativeLayout) findViewById(R.id.rl_clear);
        rl_yinsi_xiyi = (RelativeLayout) findViewById(R.id.rl_yinsi_xiyi);
        rlAbout = (RelativeLayout) findViewById(R.id.rl_about);
        settingSwitchLanguageLl = (RelativeLayout) findViewById(R.id.setting_switch_language_ll);
        tvLangHint = (TextView) findViewById(R.id.tv_lang_hint);
        sound_cb = (SwitchView) findViewById(R.id.more_sound);
        vibrate_cb = (SwitchView) findViewById(R.id.more_vibrate);
        wifi_up_cb = (SwitchView) findViewById(R.id.more_wifi_up);
        openUploadLog = (SwitchView) findViewById(R.id.open_uplaod_log);
        rlNfc = (RelativeLayout) findViewById(R.id.rl_nfc);
        rlNewTaskSound = (RelativeLayout) findViewById(R.id.rl_new_task_sound);
        rlGrabTaskSound = (RelativeLayout) findViewById(R.id.rl_grab_task_sound);
        rlMessageNoticeSound = (RelativeLayout) findViewById(R.id.rl_message_notice_sound);
        tvNewSound = (TextView) findViewById(R.id.tv_new_sound);
        tvGrabSound = (TextView) findViewById(R.id.tv_grab_sound);
        tvMessageSound = (TextView) findViewById(R.id.tv_message_sound);
        tvData = (TextView) findViewById(R.id.tv_data);

        rlMessageNoticeSound = (RelativeLayout) findViewById(R.id.rl_expire_sound);
        tv_expire_sound = (TextView) findViewById(R.id.tv_expire_sound);
        //获取多语言菜单

        DDTypeBean recordsBean = PreferencesHelper.getData(DDTypeBean.class);
        if (recordsBean != null) {
            langArrayList.addAll(recordsBean.getRecords());
        }
        presenter.getLang();
    }

    /**
     * 侧滑的开关按钮
     */
    private void onSwitchListener() {
        //声音
        sound_cb.setOnStateChangedListener(new SwitchView.OnStateChangedListener() {
            @Override
            public void toggleToOn() {
                sound_cb.setState(true);
                sharedPrefs.edit().putBoolean(Constant.SOUND, true).apply();
            }

            @Override
            public void toggleToOff() {
                sound_cb.setState(false);
                sharedPrefs.edit().putBoolean(Constant.SOUND, false).apply();
            }
        });
        //震动
        vibrate_cb.setOnStateChangedListener(new SwitchView.OnStateChangedListener() {
            @Override
            public void toggleToOn() {
                vibrate_cb.setState(true);
                sharedPrefs.edit().putBoolean(Constant.VIBRATE, true).apply();
            }

            @Override
            public void toggleToOff() {
                vibrate_cb.setState(false);
                sharedPrefs.edit().putBoolean(Constant.VIBRATE, false).apply();
            }
        });
        //wifi设置
        wifi_up_cb.setOnStateChangedListener(new SwitchView.OnStateChangedListener() {
            @Override
            public void toggleToOn() {
                wifi_up_cb.setState(true);
                sharedPrefs.edit().putBoolean(Constant.WIFI_UP, true).apply();
            }

            @Override
            public void toggleToOff() {
                wifi_up_cb.setState(false);
                sharedPrefs.edit().putBoolean(Constant.WIFI_UP, false).apply();
            }
        });
        //开启调试模式
        openUploadLog.setOnStateChangedListener(new SwitchView.OnStateChangedListener() {
            @Override
            public void toggleToOn() {
                openUploadLog.setState(true);
                sharedPrefs.edit().putBoolean(Constant.OPEN_START_MODE, true).apply();
//                CustomActivityOnCrash.install(this);
//                CustomActivityOnCrash.setShowErrorDetails(true);
            }

            @Override
            public void toggleToOff() {
                openUploadLog.setState(false);
                sharedPrefs.edit().putBoolean(Constant.OPEN_START_MODE, false).apply();
            }
        });
    }

    @Override
    protected SettingPresenter createPresenter() {
        return new SettingPresenter();
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.rl_feedback) {
            startActivity(new Intent(getViewContext(), FeedBackActivity.class));
        } else if (v.getId() == R.id.rl_nfc) {
            startActivity(new Intent(getViewContext(), NFCActivity.class));
        } else if (v.getId() == R.id.rl_about) {
            startActivity(new Intent(getViewContext(), AboutActivity.class));
        } else if (v.getId() == R.id.setting_switch_language_ll) {
            showLangDialog();
        } else if (v.getId() == R.id.rl_new_task_sound) {
            Intent intent = new Intent(this, SoundSettingAcitivity.class);
            intent.putExtra("type", "new");
            startActivityForResult(intent, NEW_CODE);
        } else if (v.getId() == R.id.rl_grab_task_sound) {
            Intent intent2 = new Intent(this, SoundSettingAcitivity.class);
            intent2.putExtra("type", "grab");
            startActivityForResult(intent2, GRAB_CODE);
        } else if (v.getId() == R.id.rl_message_notice_sound) {
            Intent intent3 = new Intent(this, SoundSettingAcitivity.class);
            intent3.putExtra("type", "message");
            startActivityForResult(intent3, MESSAGE_CODE);
        } else if (v.getId() == R.id.rl_expire_sound) {
            Intent intent3 = new Intent(this, SoundSettingAcitivity.class);
            intent3.putExtra("type", "expire");
            startActivityForResult(intent3, EXPIRE_CODE);
        } else if (v.getId() == R.id.rl_yinsi_xiyi) {
            Intent intent = new Intent(this, CommonWebActivity.class);
            startActivity(intent);
        } else if (v.getId() == R.id.rl_clear) {
            final GPSCustomDialog customDialog = new GPSCustomDialog(this, getString(R.string.confirm_clear_cache), getString(R.string.confirm_clear_cache_content));
            customDialog.show();
            customDialog.setClicklistener(new GPSCustomDialog.ClickListenerInterface() {
                @Override
                public void doConfirm() {
                    customDialog.dismiss();
                    showLoading();
                    clearX5Cache();
                    new Thread(new ClearCache()).start();
                }

                @Override
                public void doCancel() {
                    customDialog.dismiss();
                }
            });
        } else if (v.getId() == R.id.notify_setting) {
//            startActivity(new Intent(this, NotifySettingActivity.class));
            SystemSetting systemSetting = PreferencesHelper.getData(SystemSetting.class);
            if (systemSetting == null) {
                ToastUtils.showShort(context, context.getResources().getString(R.string.pls_call_admin));
                return;
            }
            if (TextUtils.isEmpty(systemSetting.getRecord().getAPP_VOICE_SIZE())) {
                ToastUtils.showShort(context, context.getResources().getString(R.string.pls_call_admin));
                return;
            }
            Intent intent = new Intent(context, SettingGuideActivity.class);
            intent.putExtra("url", systemSetting.getRecord().getAPP_VOICE_SIZE());
            context.startActivity(intent);
        } else if (v.getId() == R.id.upload_log) {
            startActivity(new Intent(this, UploadLogActivity.class));
        }
    }

    private void showLangDialog() {
        final LangDialog langDialog = new LangDialog(this, langArrayList);
        langDialog.show();
        langDialog.setOnItemClicklistener(new LangDialog.ClickListenerInterface() {
            @Override
            public void onItemClick(int postion) {
                int which = 0;
                String code = "";
                if (langArrayList.get(postion).getCode().equalsIgnoreCase("zh-CN")) {
                    which = 0;
                    code = langArrayList.get(postion).getCode();
                } else if (langArrayList.get(postion).getCode().equalsIgnoreCase("EN-US")) {
                    which = 1;
                    code = langArrayList.get(postion).getCode();
                } else if (langArrayList.get(postion).getCode().equalsIgnoreCase("zh-CHT")) {
                    which = 2;
                    code = langArrayList.get(postion).getCode();
                }

                Log.e("huohuohuohuohuo++++",FMCApplication.currentLanguage+"--------------------"+which);
                if (which != FMCApplication.currentLanguage){
                    FMCApplication.currentLanguage = which;
                    FMCApplication.currentLanguageIsChange = true;
                }

                presenter.setLangList(which, code);
                langDialog.dismiss();
            }
        });
    }

//    /**ll,dlc
//     * 语言切换
//     */
//    @Override
//    protected Dialog onCreateDialog(int id) {
//        AlertDialog.Builder builder = new AlertDialog.Builder(this);
//        switch (id) {
//            case LANG_DIALOG:
//                builder.setTitle(getString(R.string.language));
//                builder.setSingleChoiceItems(langArray, selectLang, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialogs = dialog;
//                        if (which == selectLang) {
//                            return;
//                        }
//                        presenter.setLangList(which,getResources().getStringArray(R.array.multi_language_code)[which]);
//                    }
//                });
//                break;
//            default:
//                break;
//        }
//        return builder.create();
//    }


    /**
     * 提示音设置的返回结果
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case NEW_CODE:
                    tvNewSound.setText(data.getStringExtra("name"));//新任务
                    break;
                case GRAB_CODE:
                    tvGrabSound.setText(data.getStringExtra("name"));//抢单
                    break;
                case MESSAGE_CODE:
                    tvMessageSound.setText(data.getStringExtra("name"));//消息公告
                    break;
                case EXPIRE_CODE:
                    tv_expire_sound.setText(data.getStringExtra("name"));
                    break;
            }
        }
    }

    @Override
    public void setLangListSuccess(int which, String code) {

        //语言切换
        Language.switchLanguage(context, Language.getLocal(which));
        sharedPrefs.edit().putInt("lang", which).apply();
        sharedPrefs.edit().putString("lang_code", code).apply();
        startHome();
    }

    @Override
    public void setLangListError() {
//        dialogs.dismiss();
        ToastMessage(R.string.network_error);
    }

    @Override
    public void getLangSuccess(DDTypeBean baseData) {
        PreferencesHelper.saveData(baseData);
        langArrayList.clear();
        langArrayList.addAll(baseData.getRecords());

    }


    /**
     * 开启线程清除数据
     */
    class ClearCache implements Runnable {
        @Override
        public void run() {
            try {
                /**清理localStorage缓存*/
                sharedPrefs.edit().putBoolean(Constant.CLEAR_LOCAL_STORAGE, true).apply();
                //点击注销后将此值重置为0
                sharedPrefs.edit().putString(Constant.UPLOADED_OFFLINE_DATA, "0").apply();
                databaseManager.deleteAllData();
                /**删除localStorage缓存*/
//                FileUtil.deleteLocalStorageFile(context);
                CacheDataManager.clearAllCache(SettingActivity.this);
                Thread.sleep(1000);
                handler.sendEmptyMessage(0);
            } catch (Exception e) {
                handler.sendEmptyMessage(1);
                return;
            }
        }
    }

    private void startHome() {
        Utility.startLoginActivityForH5Home(SettingActivity.this);
    }

    // 清除 X5 内核的缓存
    public void clearX5Cache() {
        // 清除 WebView 缓存
        Log.e("111缓存", "111");
        QbSdk.clearAllWebViewCache(getApplicationContext(), true);
        // 清除 WebStorage 缓存
        WebStorage.getInstance().deleteAllData();
        // 清除 WebIconDatabase 缓存
        WebIconDatabase.getInstance().removeAllIcons();
        // 清除 Cookie
        CookieSyncManager.createInstance(getApplicationContext());
        CookieSyncManager.getInstance().startSync();
        CookieManager.getInstance().removeAllCookie();
        CookieSyncManager.getInstance().sync();
        CacheHelper.getInstance().clearCatch();
    }
}